/*
 * Copyright (c) 2014 - 2017. Company.Domain Co.Ltd. All rights reserved.
 */

package cn.com.dhc.danlu.activity.goods;

import android.annotation.SuppressLint;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.IntentFilter;
import android.graphics.drawable.BitmapDrawable;
import android.net.Uri;
import android.os.Bundle;
import android.text.SpannableString;
import android.text.Spanned;
import android.text.TextUtils;
import android.text.style.ForegroundColorSpan;
import android.util.TypedValue;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.PopupWindow;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.facebook.drawee.drawable.ScalingUtils.ScaleType;
import com.facebook.drawee.view.SimpleDraweeView;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import cn.com.dhc.danlu.R;
import cn.com.dhc.danlu.activity.BaseActivity;
import cn.com.dhc.danlu.business.shopcar.activity.ShopCarActivity;
import cn.com.dhc.danlu.dlware.OperatorUtils;
import cn.com.dhc.danlu.dlware.net.GeneralBusinessObserver;
import cn.com.dhc.danlu.model.GoodInfoModel;
import cn.com.dhc.danlu.util.CommonConst;
import cn.com.dhc.danlu.util.CommonUtils;
import cn.com.dhc.danlu.util.TipCountUtil;
import cn.com.dhc.danlu.util.ToastUtil;
import cn.com.dhc.danlu.widget.BadgeView;
import cn.com.dhc.danlu.widget.banner.AutoBannerPager;
import cn.com.dhc.danlu.widget.couponview.CouponObtainPopupView;
import cn.com.dhc.danlu.widget.dialog.ViewDialog;
import cn.com.dhc.danlu.widget.home.NumEditext;
import cn.com.hd.mall.web.common.Tuple;
import cn.com.hd.mall.web.webservices.entity.BaseResponse;
import cn.com.hd.mall.web.webservices.entity.freedom.entity.coupon.ActivityEntity;
import cn.com.hd.mall.web.webservices.entity.freedom.request.base.BaseRequest;
import cn.com.hd.mall.web.webservices.entity.freedom.request.coupon.GetWithMerchReq;
import cn.com.hd.mall.web.webservices.entity.freedom.response.coupon.GetBenefitCntWithMerchResponse;
import cn.com.hd.mall.web.webservices.entity.freedom.response.coupon.ObtainDealersCouponList;
import cn.com.hd.mall.web.webservices.entity.request.merch.MerchDetailRequest;
import cn.com.hd.mall.web.webservices.entity.request.mydl.favorite.AddFavoriteRequest;
import cn.com.hd.mall.web.webservices.entity.request.mydl.favorite.DelFavoriteRequest;
import cn.com.hd.mall.web.webservices.entity.request.shoppingcart.AddShoppingCartRequest;
import cn.com.hd.mall.web.webservices.entity.response.merch.NewMerchDetailResponse;
import cn.com.hd.mall.web.webservices.entity.response.merch.NewMerchDetailResponse.NewMerchDetailModel;
import cn.com.hd.mall.web.webservices.entity.response.shoppingcart.AddShoppingcartResponse;
import cn.com.hd.mall.web.webservices.entity.response.shoppingcart.ShoppingCartSizeResponse;

import static cn.com.dhc.danlu.dlware.global.DanluApplication.agent;

/**
 * author: 刘立琦(<a href="mailto:liuliqi@danlu.com">liuliqi@danlu.com</a>)<br/>
 * version: 1.0.0<br/>
 * since: 2017-02-04 10:32<br/>
 *
 * <p>
 * 商品详情页面
 * </p>
 */
public class GoodInfoActivity extends BaseActivity {
    /**
     * 请求详细参数编码常量
     */
    private static final String REQUEST_ID = "merchandiseId";
    /**
     * 详细商品数据类名常量
     */
    private static final String INTENT_DATA = "data";
    /**
     * 1暂时缺货
     */
    private static final String OUT_STATUS = "1";
    /**
     * 2已下架
     */
    private static final String UNDER_STATUS = "2";
    /**
     * 3已失效
     */
    private static final String LOSE_STATUS = "3";
    /**
     * 4商品不存在
     */
    private static final String UNEXIST_STATUS = "4";

    /**
     * 商品名称
     */
    private TextView txtGoodName;
    /**
     * 支付方式
     */
    private TextView txtPayType;
    /**
     * 配送信息
     */
    private TextView txtDeliveryInfo;
    /**
     * 丹露价格
     */
    private TextView tvDanluPrice;
    private LinearLayout llDanluPrice;
    /**
     * 零售价格
     */
    private TextView tvRetailPrice;
    /**
     * 优惠项目数提示
     */
    private TextView tvPromotionTip;

    /**
     * 促销详情待展开容器
     */
    private LinearLayout llytCuxiaoDetail;
    /**
     * 促销rllt
     */
    private RelativeLayout rlltCuxiaoDetail;
    /**
     * 规格参数展开按钮
     */
    private ImageView imgBtnGuige;
    /**
     * 规格参数展开条
     */
    private RelativeLayout layoutGuige;
    /**
     * 规格详情信息
     */
    private TextView txtGuigeDetail;
    /**
     * 商品状态
     */
    private TextView txtGoodsState;
    /**
     * 商品规格
     */
    private TextView tv_specifications;
    /**
     * 商品描述
     */
    private RelativeLayout rllyGoodsMs;
    /**
     * 丹露保证
     */
    private RelativeLayout rllyDanluBz;
    /**
     * 商品已下架
     */
    private RelativeLayout relyGoodsStatus;
    /**
     * 收藏按钮
     */
    private LinearLayout llytShouCang;
    /**
     * 购物车按钮
     */
    private LinearLayout llytShoppingcart;
    /**
     * 加入购物车
     */
    private Button btnGoodAdd;

    private AutoBannerPager abp_banner;

    private ImageView iv_default;

    /**
     * 商品规格
     */
    private TextView tv_standard;

    /**
     * 商品详情参数ID
     */
    private String merchId;
    /**
     * 详情请求类
     */
    private MerchDetailRequest merchDetailRequest = new MerchDetailRequest();
    /**
     * 详情数据类
     */
    private NewMerchDetailResponse detailResponse = new NewMerchDetailResponse();
    /**
     * 添加购物车请求类
     */
    private AddShoppingCartRequest shoppingCartRequest = new AddShoppingCartRequest();
    /**
     * 购物车数量角标
     */
    private BadgeView bdvViewShoppingCarCount = null;
    /**
     * 为了传递给规格参数画面的数据模型类
     */
    private GoodInfoModel goodInfoModel = new GoodInfoModel();
    /**
     * 角标布局
     */
    private LinearLayout llytBadgeImg;
    /**
     * 收藏图片
     */
    private ImageView imgShouCang;
    /**
     * 收藏txt
     */
    private TextView txtShouCang;
    /**
     * 收藏状态
     */
    private boolean isCollection = false;
    /**
     * 选择数量加入购物车
     */
    private PopupWindow pwAddCar;
    /**
     * 根视图
     */
    private ViewGroup root_view;

    private TextView tv_coupon;
    private ImageView iv_coupon_more;

    private View vLineCuxiaoTop;
    private View vLineCuxiaoMiddle;
    private View vLineCuxiaoBottom;
    // 品类优化新增 lyf  2016-12-02 14:46:05
    private TextView txtMinDeliveryAmt;
    private TextView txtGoodsReturn;
    private TextView txtServerTel;
    private LinearLayout llServerTel;

    private int mMinSaleCount = 1;

    private BroadcastReceiver mBroadcastReceiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            String action = intent.getAction();
            if (CommonConst.BroadcastAction.BROADCAST_GET_SHOPPINGCART_COUNT_ACTION.equals(action)) {
                // 获取购物车数量
                // 获取购物车商品数量
                getShoppingCarCount();
            }
        }
    };
    /**
     * 点击事件监听类
     */
    private View.OnClickListener goodInfoClickListener = new View.OnClickListener() {
        Intent intent = new Intent();

        public void onClick(View v) {
            switch (v.getId()) {
                case R.id.layoutGuige:// 规格展开
                    if (txtGuigeDetail.getVisibility() == View.VISIBLE) {
                        txtGuigeDetail.setVisibility(View.GONE);
                        imgBtnGuige.setBackgroundResource(R.drawable.img_top_btn);
                    } else {
                        txtGuigeDetail.setVisibility(View.VISIBLE);
                        imgBtnGuige.setBackgroundResource(R.drawable.img_bottom_btn);
                    }
                    break;

                case R.id.llytShoppingcart:// 跳转至购物车
                    // 跳转到购物车画面
                    skipShopCartAct();
                    break;

                case R.id.rllyGoodsMs:// 商品描述
                    intent.setClass(GoodInfoActivity.this, GoodInfoInstructionActivity.class);
                    ArrayList<String> urls = new ArrayList<>();
                    urls.addAll(goodInfoModel.getImgUrl());
                    intent.putStringArrayListExtra(INTENT_DATA, urls);
                    // 跳转
                    startActivity(intent);
                    break;

                case R.id.rllyDanluBz:// 丹露保证
                    intent.setClass(GoodInfoActivity.this, GoodInfoPromiseActivity.class);
                    // 跳转
                    startActivity(intent);
                    break;

                case R.id.btnGoodAdd:// 添加商品到购物车
                    // 调用添加商品到购物车接口
                    showAddCar();
                    break;

                case R.id.llytShouCang:
                    if (isCollection) { // 默认没收藏
                        addFavourite(detailResponse.getNewMerchDetailModel());// 添加收藏
                        isCollection = false;
                    } else {
                        delFavourite(detailResponse.getNewMerchDetailModel());// 删除收藏
                        isCollection = true;
                    }
                    break;

                case R.id.iv_coupon_more: // 更多优惠券
                    getActivityListWithMerch();
                    break;

                default:
                    break;
            }
        }
    };
    private String mSpecification;


    /**
     * 获取优惠券活动列表
     */
    private void getActivityListWithMerch() {
        String token = agent.getToken();
        agent.getApi()
                .getActivityListWithMerch(new GetWithMerchReq(token, merchId))
                .compose(OperatorUtils.<ObtainDealersCouponList> defaultSchedulers())
                .subscribe(new GeneralBusinessObserver<ObtainDealersCouponList>(GoodInfoActivity.this, R.string.tips_acquiring_coupons) {
                    @Override
                    protected void onSuccess(ObtainDealersCouponList obtainDealersCouponList) {
                        List<ActivityEntity> list = obtainDealersCouponList.getActivityList();
                        if (null != list && !list.isEmpty()) {
                            tv_coupon.setText(String.format(getResources().getString(R.string.dl_goods_info_couponcnt), list.size() + ""));
                            showCouponObtainPopup(list);
                        } else {
                            tv_coupon.setText("暂无可领优惠券");
                            ToastUtil.getInstance().show("暂无可领优惠券");
                        }
                    }
                });
    }

    private void showCouponObtainPopup(List<ActivityEntity> datas) {
        CouponObtainPopupView popupView = new CouponObtainPopupView(this, root_view, datas);
        popupView.setNeedAnim(true);
        popupView.showAtLocation(root_view, Gravity.CENTER, 0, CommonUtils.getStatusBarHeight(GoodInfoActivity.this));
        popupView.setOnDismissListener(new PopupWindow.OnDismissListener() {
            @Override
            public void onDismiss() {
                getBenefitCntWithMerch(); //获取可领取优惠券个数
            }
        });
    }

    /**
     * 获取可领取优惠券数量
     */
    private void getBenefitCntWithMerch() {
        String token = agent.getToken();
        agent.getApi().getBenefitCntWithMerch(new GetWithMerchReq(token, merchId))
                .compose(OperatorUtils.<GetBenefitCntWithMerchResponse> defaultSchedulers())
                .subscribe(new GeneralBusinessObserver<GetBenefitCntWithMerchResponse>() {
                    @Override
                    protected void onSuccess(GetBenefitCntWithMerchResponse getBenefitCntWithMerchResponse) {
                        if ("0".equals(getBenefitCntWithMerchResponse.getActivityCnt()) || TextUtils.isEmpty(getBenefitCntWithMerchResponse.getActivityCnt())) {
                            tv_coupon.setText("暂无可领优惠券");
                        } else {
                            tv_coupon.setText(String.format(getResources().getString(R.string.dl_goods_info_couponcnt), getBenefitCntWithMerchResponse.getActivityCnt()));
                        }
                    }
                });
    }

    /**
     * 跳转到购物车页面
     */
    private void skipShopCartAct() {
        Intent intent = new Intent();
        intent.setClass(GoodInfoActivity.this, ShopCarActivity.class);
        intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_SINGLE_TOP);
        intent.putExtra(ShopCarActivity.FROM_ACTIVITY_FLAG, ShopCarActivity.FROM_GOOD_INFO);
        // 跳转
        startActivity(intent);
    }

    /**
     * 显示采购页
     */
    private void showAddCar() {
        //调用显示前 先设置最小起售数量
        View contentView = pwAddCar.getContentView();
        final NumEditext neCount = (NumEditext) contentView.findViewById(R.id.ne_count);
        neCount.setDefaultCount(mMinSaleCount);
        pwAddCar.showAtLocation(root_view, Gravity.CENTER, 0, CommonUtils.getStatusBarHeight(GoodInfoActivity.this));
        CommonUtils.dimBackground(GoodInfoActivity.this, 1.0f, 0.5f);
    }

    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_good_info);

        initViews();
        initArgs();
    }

    private void initViews() {
        vLineCuxiaoTop = findViewById(R.id.vLineCuxiaoTop);
        vLineCuxiaoMiddle = findViewById(R.id.vLineCuxiaoMiddle);
        vLineCuxiaoBottom = findViewById(R.id.vLineCuxiaoBottom);

        txtGoodName = (TextView) findViewById(R.id.txtGoodName);
        txtPayType = (TextView) findViewById(R.id.txtPayType);
        txtDeliveryInfo = (TextView) findViewById(R.id.txtDeliveryInfo);
        tvDanluPrice = (TextView) findViewById(R.id.tvDanluPrice);
        tvRetailPrice = (TextView) findViewById(R.id.tvRetailPrice);
        tvPromotionTip = (TextView) findViewById(R.id.tvPromotionTip);
        txtGuigeDetail = (TextView) findViewById(R.id.txtGuigeDetail);
        txtGoodsState = (TextView) findViewById(R.id.txtGoodsState);
        tv_specifications = (TextView) findViewById(R.id.tv_specifications);
        tv_standard = (TextView) findViewById(R.id.tv_standard);
        txtShouCang = (TextView) findViewById(R.id.txtShouCang);
        tv_coupon = (TextView) findViewById(R.id.tv_coupon);
        txtMinDeliveryAmt = (TextView) findViewById(R.id.txtMinDeliveryAmt);
        txtGoodsReturn = (TextView) findViewById(R.id.txtGoodsReturn);
        txtServerTel = (TextView) findViewById(R.id.txtServerTel);

        llDanluPrice = (LinearLayout) findViewById(R.id.llDanluPrice);
        llytCuxiaoDetail = (LinearLayout) findViewById(R.id.llytCuxiaoDetail);
        llytShouCang = (LinearLayout) findViewById(R.id.llytShouCang);
        llytShoppingcart = (LinearLayout) findViewById(R.id.llytShoppingcart);
        llytBadgeImg = (LinearLayout) findViewById(R.id.llytBadgeImg);
        llServerTel = (LinearLayout) findViewById(R.id.llServerTel);

        rlltCuxiaoDetail = (RelativeLayout) findViewById(R.id.rlltCuxiaoDetail);
        layoutGuige = (RelativeLayout) findViewById(R.id.layoutGuige);
        rllyGoodsMs = (RelativeLayout) findViewById(R.id.rllyGoodsMs);
        rllyDanluBz = (RelativeLayout) findViewById(R.id.rllyDanluBz);
        relyGoodsStatus = (RelativeLayout) findViewById(R.id.relyGoodsStatus);

        imgBtnGuige = (ImageView) findViewById(R.id.imgBtnGuige);
        iv_default = (ImageView) findViewById(R.id.iv_default);
        imgShouCang = (ImageView) findViewById(R.id.imgShouCang);
        iv_coupon_more = (ImageView) findViewById(R.id.iv_coupon_more);

        btnGoodAdd = (Button) findViewById(R.id.btnGoodAdd);
        abp_banner = (AutoBannerPager) findViewById(R.id.abp_banner);
        root_view = (ViewGroup) findViewById(R.id.root_view);
    }

    @Override
    protected String getActivityTitle() {
        return null;
    }

    /**
     * 注册获取发送购物车数量的广播通知
     */
    public void registerBoradcastReceiver() {
        registerReceiver(mBroadcastReceiver, new IntentFilter(CommonConst.BroadcastAction.BROADCAST_GET_SHOPPINGCART_COUNT_ACTION));
    }

    /**
     * 画面初始化
     */
    private void initArgs() {
        Bundle bundle = getIntent().getExtras();
        // 得到请求商品编码
        merchId = bundle.getString(REQUEST_ID);
        // 设置请求商品编码参数
        merchDetailRequest.setMerchId(merchId);
        // 设置请求Token参数
        merchDetailRequest.setToken(agent.getToken());
        // 调用商品详细接口
        agent.getApi().getMerchandisesDetail(merchDetailRequest)
                .compose(OperatorUtils.<NewMerchDetailResponse> defaultSchedulers())
                .subscribe(new GeneralBusinessObserver<NewMerchDetailResponse>(GoodInfoActivity.this, R.string.loading_common_msg) {
                    @Override
                    protected void onSuccess(NewMerchDetailResponse newMerchDetailResponse) {
                        detailResponse = newMerchDetailResponse;
                        if (null != detailResponse.getNewMerchDetailModel().getAlbumPicUrl() && detailResponse.getNewMerchDetailModel().getAlbumPicUrl().size() >= 1) {
                            goodInfoModel.setImgUrl(detailResponse.getNewMerchDetailModel().getDetailPicUrl());
                        }
                        updateUI(detailResponse.getNewMerchDetailModel()); // 更新画面
                    }

                    @Override
                    protected void onAlertTips(String displayMessage) {
                        ToastUtil.getInstance().show(TextUtils.isEmpty(displayMessage) ? "商品详情数据获取失败" : displayMessage);
                    }
                });

        // 获取购物车商品数量
        getShoppingCarCount();
        // 商品详情：可领优惠券个数(与商品绑定)
        getBenefitCntWithMerch();
        registerBoradcastReceiver();
    }

    /**
     * 获取购物车商品数量
     */
    private void getShoppingCarCount() {
        BaseRequest request = new BaseRequest();
        request.setToken(agent.getToken());
        agent.getApi().getShoppingCartCount(request).compose(OperatorUtils.<ShoppingCartSizeResponse> defaultSchedulers())
                .subscribe(new GeneralBusinessObserver<ShoppingCartSizeResponse>() {
                    @Override
                    protected void onSuccess(ShoppingCartSizeResponse shoppingCartSizeResponse) {
                        updateBdvViewShoppingCarCount(shoppingCartSizeResponse.getShoppingCartSize());
                    }

                    @Override
                    protected void onAlertTips(String displayMessage) {
                        ToastUtil.getInstance().show(TextUtils.isEmpty(displayMessage) ? displayMessage : GoodInfoActivity.this.getString(R.string.tips_get_shopcart_count_failed));
                    }
                });
    }

    /**
     * 通过接口返回的商品详细数据来更新画面
     */
    private void updateUI(final NewMerchDetailModel response) {
        // 判断商品是否存在
        if (!response.getMerchStatus().equals("0") && !response.getMerchStatus().equals("1")) {
            relyGoodsStatus.setVisibility(View.VISIBLE);
            return;
        }
        // 设置监听事件
        setLisetListener();
        // 设置预览商品图片
        initViewPager();
        // 设置加入购物车弹出菜单
        initPopupViewAddCar(response);
        // 返回0成功或有信息
        String SUCCESS = "0";
        // 设置商品状态--0正常 1缺货
        if (response.getMerchStatus() != null) {
            txtGoodsState.setVisibility(View.VISIBLE);
            if (response.getMerchStatus().equals(SUCCESS)) {
                txtGoodsState.setText("货源充足");
            } else if (response.getMerchStatus().equals(OUT_STATUS)) {
                txtGoodsState.setText("暂时缺货");
                btnGoodAdd.setText("缺 货");
                btnGoodAdd.setOnClickListener(null);
            } else if (response.getMerchStatus().equals(UNDER_STATUS)) {
                txtGoodsState.setText("已下架");
            } else if (response.getMerchStatus().equals(LOSE_STATUS)) {
                txtGoodsState.setText("商品已失效");
            } else if (response.getMerchStatus().equals(UNEXIST_STATUS)) {
                txtGoodsState.setText("商品不存在");
            } else {
                txtGoodsState.setVisibility(View.GONE);
            }
        } else {
            txtGoodsState.setVisibility(View.GONE);
        }
        // 商品名称
        txtGoodName.setText(response.getMerchName());
        // 配送信息
        txtDeliveryInfo.setText("由 " + response.getSellerName() + " 负责销售及配送");
        // 最小起送金额
        if (!TextUtils.isEmpty(response.getMinDeliveryAmt())) {
            txtMinDeliveryAmt.setText(String.format(getResources().getString(R.string.min_delivery_amt), CommonUtils.fenToYuan(new BigDecimal(response.getMinDeliveryAmt()))));
            txtMinDeliveryAmt.setVisibility(View.VISIBLE);
        }
        // 是否可以退货
        if ("0".equals(response.getReturnFlag()) || TextUtils.isEmpty(response.getReturnFlag())) {
            txtGoodsReturn.setVisibility(View.GONE);
        } else {
            txtGoodsReturn.setVisibility(View.VISIBLE);
            txtGoodsReturn.setText(R.string.non_return);
        }
        // 经销商客服电话
        if (TextUtils.isEmpty(response.getServerTel())) {
            llServerTel.setVisibility(View.GONE);
        } else {
            llServerTel.setVisibility(View.VISIBLE);
            txtServerTel.setText(response.getServerTel());
            txtServerTel.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    // 直接拨打电话 | 打开拨号界面 此处直接拨打电话
                    new ViewDialog.Builder(GoodInfoActivity.this).setMessage(response.getServerTel()).setNegativeButton(R.string.btn_cancel, new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialog, int which) {
                            dialog.dismiss();
                        }
                    }).setPositiveButton(R.string.btn_confirm, new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialog, int which) {
                            CommonUtils.callPhone(GoodInfoActivity.this, response.getServerTel());
                            dialog.dismiss();
                        }
                    }).create().show();
                }
            });
        }
        // 支付方式及增值税描述
        if (response.getSupportCod().equals(SUCCESS)) {
            txtPayType.setText("支持货到付款");
        } else {
            txtPayType.setText("暂不支持货到付款");
        }
        // 设置商品价格
        String danluPrice = CommonUtils.fenToYuan(new BigDecimal(response.getDanluPrice())).toPlainString();
        tvDanluPrice.setText(danluPrice);
        tv_specifications.setText("/" + response.getMerchSpec());
        llDanluPrice.setVisibility(View.VISIBLE);
        String retailPrice = CommonUtils.fenToYuan(new BigDecimal(response.getRetailPrice())).toPlainString();
        tvRetailPrice.setText("￥" + retailPrice);
        // 有促销消息
        if (response.getPromotionList() != null && response.getPromotionList().size() > 0) {
            vLineCuxiaoMiddle.setVisibility(View.VISIBLE);
            tvPromotionTip.setText("共" + response.getPromotionList().size() + "项促销");
            tvPromotionTip.setVisibility(View.VISIBLE);
            for (String s : response.getPromotionList()) {
                createCuxiao(s);
            }
        } else { // 木有促销消息
            rlltCuxiaoDetail.setVisibility(View.GONE);
            llytCuxiaoDetail.setVisibility(View.GONE);
            vLineCuxiaoTop.setVisibility(View.GONE);
            vLineCuxiaoMiddle.setVisibility(View.GONE);
            vLineCuxiaoBottom.setVisibility(View.GONE);
        }

        // 规格参数
        txtGuigeDetail.setText(getPropertyDesc(detailResponse.getNewMerchDetailModel()));
        txtGuigeDetail.setVisibility(View.VISIBLE);
        imgBtnGuige.setBackgroundResource(R.drawable.img_bottom_btn);
        // 商品描述
        // 获取是否收藏
        if (response.getIsFavorite().equals(SUCCESS)) {
            imgShouCang.setImageResource(R.drawable.img_shoucang_a);
            txtShouCang.setText(getResources().getString(R.string.good_is_favourite));
            isCollection = false;
        } else {
            imgShouCang.setImageResource(R.drawable.img_shoucang_n);
            txtShouCang.setText(getResources().getString(R.string.good_no_favourite));
            isCollection = true;
        }
        if (!TextUtils.isEmpty(mSpecification) && !TextUtils.isEmpty(response.getMerchSpec()) && !response.getMerchSpec().equals(mSpecification)) {
            tv_standard.setText("(1" + response.getMerchSpec() + response.getUnitsConvertion() + mSpecification + ")");
        }
    }

    /**
     * 设置按钮的监听方法
     */
    private void setLisetListener() {
        // 促销展开按钮监听
        rlltCuxiaoDetail.setOnClickListener(goodInfoClickListener);
        // 规格展开按钮监听
        layoutGuige.setOnClickListener(goodInfoClickListener);
        // 商品描述响应
        rllyGoodsMs.setOnClickListener(goodInfoClickListener);
        // 丹露保证响应
        rllyDanluBz.setOnClickListener(goodInfoClickListener);
        // 收藏按钮
        llytShouCang.setOnClickListener(goodInfoClickListener);
        // 购物车按钮
        llytShoppingcart.setOnClickListener(goodInfoClickListener);
        // 加入购物车按钮
        btnGoodAdd.setOnClickListener(goodInfoClickListener);
        // 更多优惠券领取
        iv_coupon_more.setOnClickListener(goodInfoClickListener);
    }

    /**
     * 初始化商品图片浏览器
     */
    @SuppressLint("InlinedApi")
    private void initViewPager() {
        // 存放图片的List
        List<String> goodImgs = new ArrayList<>();
        if (detailResponse.getNewMerchDetailModel().getAlbumPicUrl() != null && detailResponse.getNewMerchDetailModel().getAlbumPicUrl().size() >= 1) {
            // 如果有详细图片那么就依次下载并添加到List中
            goodImgs.addAll(detailResponse.getNewMerchDetailModel().getAlbumPicUrl());
        }

        if (!goodImgs.isEmpty()) {
            abp_banner.setScaleType(ScaleType.CENTER_INSIDE);
            abp_banner.setVisibility(View.VISIBLE);
            abp_banner.refreshBanner(goodImgs);
            iv_default.setVisibility(View.GONE);
        } else {
            abp_banner.setVisibility(View.GONE);
            iv_default.setVisibility(View.VISIBLE);
        }
    }

    /**
     * 初始化加入购物车的弹出菜单
     */
    private void initPopupViewAddCar(final NewMerchDetailModel response) {
        View popView = ((LayoutInflater) getSystemService(LAYOUT_INFLATER_SERVICE)).inflate(R.layout.popview_good_info, root_view, false);
        pwAddCar = new PopupWindow(popView, ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT, true);
        pwAddCar.setBackgroundDrawable(new BitmapDrawable());
        pwAddCar.setAnimationStyle(R.style.popwin_anim_style);
        pwAddCar.setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_ADJUST_RESIZE);
        pwAddCar.setOnDismissListener(new PopupWindow.OnDismissListener() {
            @Override
            public void onDismiss() {
                CommonUtils.dimBackground(GoodInfoActivity.this, 0.5f, 1.0f);
            }
        });

        final NumEditext neCount = (NumEditext) popView.findViewById(R.id.ne_count);
        SimpleDraweeView sdvProduct = (SimpleDraweeView) popView.findViewById(R.id.sdv_product);
        TextView tvProductName = (TextView) popView.findViewById(R.id.tv_product_name);
        int count = Integer.valueOf(response.getMinSaleNumber());
        mMinSaleCount = count;
        neCount.setMinCount(count);
        neCount.setDefaultCount(count);
        if (!TextUtils.isEmpty(response.getPicUrl())) {
            sdvProduct.setImageURI(Uri.parse(response.getPicUrl()));
        }
        tvProductName.setText(response.getMerchName());
        popView.findViewById(R.id.iv_cancel).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (pwAddCar.isShowing()) {
                    pwAddCar.dismiss();
                    CommonUtils.hideSoftInputForce(GoodInfoActivity.this);
                }
            }
        });
        popView.findViewById(R.id.btn_commit).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                String res = neCount.getText().trim();
                if (TextUtils.isEmpty(res)) {
                    ToastUtil.getInstance().show("请输入购买数量");
                    return;
                }
                long value = Long.parseLong(res);
                if (value < mMinSaleCount) {
                    ToastUtil.getInstance().show("购买数量不能小于" + mMinSaleCount);
                    return;
                }
                addGoodsToShoppingCar(response, neCount.getText().trim());
            }
        });

        popView.findViewById(R.id.pop_root).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (pwAddCar.isShowing()) {
                    pwAddCar.dismiss();
                    CommonUtils.hideSoftInputForce(GoodInfoActivity.this);
                }
            }
        });
    }

    /**
     * 创建促销图片和文字
     */
    private void createCuxiao(String cuxiaoTxt) {
        // 新建图片
        ImageView imageView = new ImageView(this);
        imageView.setImageResource(R.drawable.icon_home_cu);
        LinearLayout.LayoutParams imageLp = new LinearLayout.LayoutParams(CommonUtils.dipToPx(this, 12), CommonUtils.dipToPx(this, 12));
        imageLp.setMargins(0, 5, 4, 0);
        imageView.setLayoutParams(imageLp);
        // 新建布局
        LinearLayout llytCuxiaoDetailMz = new LinearLayout(this);
        llytCuxiaoDetailMz.setPadding(0, getResources().getDimensionPixelSize(R.dimen.dl_4), 0, 0);
        LinearLayout.LayoutParams llytLp = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.WRAP_CONTENT);
        llytCuxiaoDetailMz.setLayoutParams(llytLp);
        llytCuxiaoDetailMz.setOrientation(LinearLayout.HORIZONTAL);
        llytCuxiaoDetailMz.addView(imageView);
        llytCuxiaoDetailMz.addView(renderText(cuxiaoTxt));
        // 添加子布局
        llytCuxiaoDetail.addView(llytCuxiaoDetailMz);
        llytCuxiaoDetail.setVisibility(View.VISIBLE);
    }

    /**
     * 获取规格信息
     */
    private String getPropertyDesc(NewMerchDetailModel response) {
        StringBuilder sb = new StringBuilder();
        for (int i = 0, len = response.getPropertyList().size(); i < len; i++) {
            Tuple<String, String> tuple = response.getPropertyList().get(i);
            String key = tuple.getFirstValue();
            if (key.contains("包装规格")) {
                mSpecification = tuple.getSecondValue();
            }
            sb.append(tuple.getFirstValue());
            sb.append(getString(R.string.char_sign));
            sb.append(tuple.getSecondValue());
            if (i != (len - 1)) {
                sb.append("\n");
            }
        }

        return sb.toString();
    }

    /**
     * 添加商品到购物车
     */
    private void addGoodsToShoppingCar(NewMerchDetailModel response, String merchCount) {
        // 设置Token
        shoppingCartRequest.setToken(agent.getToken());
        // 设置商品ID
        shoppingCartRequest.setMerchId(response.getMerchId());
        // 卖家ID
        shoppingCartRequest.setSellerId(response.getSellerId());
        // 卖家名字
        shoppingCartRequest.setSellerName(response.getSellerName());
        // 购买的数量
        shoppingCartRequest.setMerchCount(merchCount);
        // 加入购物车
        agent.getApi().addShoppingCartNew(shoppingCartRequest).compose(OperatorUtils.<AddShoppingcartResponse> defaultSchedulers())
                .subscribe(new GeneralBusinessObserver<AddShoppingcartResponse>(GoodInfoActivity.this, R.string.tips_adding_shopping_cart) {
                    @Override
                    protected void onSuccess(AddShoppingcartResponse addShoppingcartResponse) {
                        ToastUtil.getInstance().show(R.string.add_shopping_cart_success);
                        // 获取购物车商品数量
                        getShoppingCarCount();
                        if (null != pwAddCar && pwAddCar.isShowing()) {
                            pwAddCar.dismiss();
                            CommonUtils.hideSoftInputForce(GoodInfoActivity.this);
                        }
                    }

                    @Override
                    protected String parseBussinessException(String code) {
                        String displayMsg = "";
                        switch (code) {
                            case "1": // 商品无售卖权
                                displayMsg = getString(R.string.add_shopping_cart_error_1);
                                break;
                            case "2": // 商品库存不足
                                displayMsg = getString(R.string.add_shopping_cart_error_3);
                                break;
                            case "3": // 商品种类超过限制
                                displayMsg = getString(R.string.add_shopping_cart_error_2);
                                break;
                            case "4": //商品已经下架
                                displayMsg = getString(R.string.add_shopping_cart_error_4);
                                break;
                            default:
                                displayMsg = getString(R.string.tips_add_shopcart_failed);
                                break;

                        }
                        return displayMsg;
                    }

                    @Override
                    protected void onAlertTips(String displayMessage) {
                        ToastUtil.getInstance().show(TextUtils.isEmpty(displayMessage) ? "加入购物车失败！" : displayMessage);
                    }
                });

    }

    /**
     * 渲染TextView中指定字段
     */
    private TextView renderText(String str) {
        TextView tv = new TextView(this);

        String rex = "\\[([^\\[\\]]*)\\]";
        String str2 = str.replace("[", "").replace("]", "");
        SpannableString s = new SpannableString(str);
        SpannableString s2 = new SpannableString(str2);

        Pattern p = Pattern.compile(rex);
        Matcher m = p.matcher(s);

        int i = 0;
        while (m.find()) {
            int start = m.start();
            int end = m.end();
            int dx = end - start - 2;
            if (i != 0) {
                start = start - i * 2;
            }
            s2.setSpan(new ForegroundColorSpan(getResources().getColor(R.color.color_b12525)), start, start + dx, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
            i++;
        }

        tv.setText(s2);
        LinearLayout.LayoutParams txtLp = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.WRAP_CONTENT);
        txtLp.setMargins(5, 0, 0, 0);
        tv.setTextSize(TypedValue.COMPLEX_UNIT_SP, 12);
        tv.setLayoutParams(txtLp);
        return tv;
    }

    /**
     * 自定义吐司
     *
     * @param txt
     *         想弹出的文字内容
     */
    @SuppressLint("InflateParams")
    private void createToast(String txt) {
        // 得到布局Inflater
        LayoutInflater inflater = this.getLayoutInflater();
        // 加载自定义布局
        View view = inflater.inflate(R.layout.view_good_info_toast, null);
        // 实例化文本框
        TextView txtToastContent = (TextView) view.findViewById(R.id.txtToastContent);
        // 设置文本框内容
        txtToastContent.setText(txt);
        // 创建吐司实例
        Toast toast = new Toast(this);
        // 设置吐司显示的位置
        toast.setGravity(Gravity.BOTTOM, 0, 80);
        // 设置吐司显示时间
        toast.setDuration(Toast.LENGTH_SHORT);
        // 吐司设置布局
        toast.setView(view);
        // 显示自定义吐司
        toast.show();
    }

    /**
     * 更新购物车角标数量
     */
    private void updateBdvViewShoppingCarCount(int count) {
        // 设置角标
        if (bdvViewShoppingCarCount == null) {
            bdvViewShoppingCarCount = new BadgeView(GoodInfoActivity.this, llytBadgeImg);
        }

        bdvViewShoppingCarCount.setText(TipCountUtil.cover(count, TipCountUtil.SMALL_FLAG));
        bdvViewShoppingCarCount.setBadgeMargin(0, 0);
        bdvViewShoppingCarCount.setTextSize(10);
        bdvViewShoppingCarCount.setText(String.valueOf(count));
        if (count < 1) {
            bdvViewShoppingCarCount.hide();
        } else {
            bdvViewShoppingCarCount.show();
        }
    }

    /***
     * 添加收藏
     */
    private void addFavourite(NewMerchDetailModel response) {
        // 请求对象
        AddFavoriteRequest addFavoriteRequest = new AddFavoriteRequest();
        // 设置token
        addFavoriteRequest.setToken(agent.getToken());
        // 设置商品id
        addFavoriteRequest.setMerchId(response.getMerchId());
        // 添加收藏
        agent.getApi().addFavourite(addFavoriteRequest).compose(OperatorUtils.defaultSchedulers())
                .subscribe(new GeneralBusinessObserver<BaseResponse>(GoodInfoActivity.this, R.string.tips_favourite_adding) {
                    @Override
                    protected void onSuccess(BaseResponse baseResponse) {
                        createToast(getString(R.string.good_info_save_shop_suceed_prompt));
                        imgShouCang.setImageResource(R.drawable.img_shoucang_a);
                        txtShouCang.setText(getResources().getString(R.string.good_is_favourite));
                    }

                    @Override
                    protected String parseBussinessException(String code) {
                        String displayMsg = "";
                        if (code.equals("2")) { // 重复收藏
                            displayMsg = getString(R.string.good_info_has_save_shop_suceed_prompt);
                            imgShouCang.setImageResource(R.drawable.img_shoucang_a);
                            txtShouCang.setText(getResources().getString(R.string.good_is_favourite));
                        } else {
                            displayMsg = getString(R.string.good_info_save_shop_failed_prompt);
                            imgShouCang.setImageResource(R.drawable.img_shoucang_n);
                            txtShouCang.setText(getResources().getString(R.string.good_no_favourite));
                        }
                        return displayMsg;
                    }

                    @Override
                    protected void onAlertTips(String displayMessage) {
                        ToastUtil.getInstance().show(TextUtils.isEmpty(displayMessage) ? "添加收藏失败！" : displayMessage);
                    }
                });
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();

        unregisterReceiver(mBroadcastReceiver);
    }

    /***
     * 删除收藏
     */
    private void delFavourite(NewMerchDetailModel response) {
        // 删除请求
        DelFavoriteRequest delFavoriteRequest = new DelFavoriteRequest();
        // 设置token
        delFavoriteRequest.setToken(agent.getToken());
        // 设置商品id
        // 删除收藏
        List<String> merchIds = new ArrayList<>();
        merchIds.add(response.getMerchId());
        delFavoriteRequest.setMerchId(merchIds);
        // 删除收藏
        agent.getApi().delFavourite(delFavoriteRequest).compose(OperatorUtils.defaultSchedulers())
                .subscribe(new GeneralBusinessObserver<BaseResponse>(GoodInfoActivity.this, R.string.tips_favourite_deleting) {
                    @Override
                    protected void onSuccess(BaseResponse baseResponse) {
                        createToast(getString(R.string.good_info_del_shop_suceed_prompt));
                        imgShouCang.setImageResource(R.drawable.img_shoucang_n);
                        txtShouCang.setText(getResources().getString(R.string.good_no_favourite));
                    }

                    @Override
                    protected String parseBussinessException(String code) {
                        imgShouCang.setImageResource(R.drawable.img_shoucang_a);
                        txtShouCang.setText(getResources().getString(R.string.good_no_favourite));
                        return getString(R.string.good_info_del_shop_failed_prompt);
                    }

                    @Override
                    protected void onAlertTips(String displayMessage) {
                        ToastUtil.getInstance().show(TextUtils.isEmpty(displayMessage) ? "删除收藏失败！" : displayMessage);
                    }
                });
    }
}